/*
 * API borrowed from http://en.urbarama.com/api
 */

package depena.urbarama.data;

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Alberto
 */
public class ProjectRepository 
{
    private final String _urbarama = "http://www.urbarama.com/api/project?";
    private String _webpage;
    private ProjectData _projectData;
    private final String _mysqlURL ="jdbc:mysql://taz.harding.edu/jdepena?user="
            + "jdepena&password=jdepena";
    
    private Database _db;
    
    /**
     * Constructor
     */
    public ProjectRepository()
    {
        //http://en.urbarama.com/api
        _webpage = _urbarama + "sort=popular&offset=0&count=100&minx=-180&"+ 
                "miny=-90&maxx=180&maxy=90&size=small&format=json";    
        try {
            try {
                Class.forName("com.mysql.jdbc.Driver").newInstance();
            } catch (InstantiationException ex) {
                Logger.getLogger(ProjectRepository.class.getName()).log(Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                Logger.getLogger(ProjectRepository.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(ProjectRepository.class.getName()).log(Level.SEVERE, null, ex);
        }
        _db = new Database(_mysqlURL); 
    }
    
    /**
     * Initialize data repository
     * 
     */
    public void buildProjectRepository()
    {
         String str = readUrl(_webpage);
         
         //http://code.google.com/p/google-gson/
         Gson gson = new Gson();
         _projectData = gson.fromJson(str, ProjectData.class);
    }
    
    /**
     * Print projects for testing purposes.
     */
    public void printProjects()
    {
        for (Project p : _projectData.getProjects())
        {
            System.out.println(p + "\n");
        }
        System.out.println("Size: " + _projectData.getProjects().size());
    }
    
    /**
     * Extract json values and insert them to database (MySql)
     * 
     * @param projectData 
     */
    public void populateDatabase()
    {
        try 
        {
            for (Project p : _projectData.getProjects())
            {
                _db.insertProject(p);
            }
        } 
        catch (Exception ex) 
        {
            System.out.println("Exception: " + ex);
        }
    }
    
    /**
     * return well defined API url.
     * 
     * @param urlString
     * @return API url (Urbarama)
     */
    private static String readUrl(String urlString)  
    {
        try 
        {
            URL url = new URL(urlString);
            BufferedReader reader = new BufferedReader(new InputStreamReader
                    (url.openStream()));
            
            StringBuilder buffer = new StringBuilder();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read); 

            if (reader != null)
                reader.close();
            
            return buffer.toString();
        } 
        catch (IOException ex) 
        {
            System.out.println("IOException: " + ex);
            return null;
        }    
    }
}
